const BaseController = require('./base_controller.js');
const QAService = require('../service/qa_service.js');

class QAController extends BaseController {

	/** 获取问答列表 */
	async getList() {
		// 数据校验
		let rules = {
			search: 'string|min:1|max:30|name=搜索条件',
			sortType: 'string|name=搜索类型',
			sortVal: 'name=搜索类型值',
			orderBy: 'object|name=排序',
			page: 'must|int|default=1',
			size: 'int',
			isTotal: 'bool',
			oldTotal: 'int',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = new QAService();
		let result = await service.getQAList(input);

		// 数据格式化
		let list = result.list;

		for (let k = 0; k < list.length; k++) {
			list[k].QUESTION = this.fmtHtml(list[k].QUESTION);
			list[k].ANSWER = this.fmtHtml(list[k].ANSWER);
		}

		return result;
	}

	/** 获取问答详情 */
	async detail() {
		// 数据校验
		let rules = {
			id: 'must|id',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = new QAService();
		let qa = await service.getQADetail(input.id);
		if (qa) {
			qa.QUESTION = this.fmtHtml(qa.QUESTION);
			qa.ANSWER = this.fmtHtml(qa.ANSWER);
		}
		return qa;
	}

	/** 提交问题 */
	async ask() {
		// 数据校验
		let rules = {
			question: 'must|string|min:1|max:500|name=问题',
		};

		// 取得数据
		let input = this.validateData(rules);
		
		let service = new QAService();
		return await service.ask(this._userId, input.question);
	}

	/** 删除问题 */
	async delete() {
		// 数据校验
		let rules = {
			id: 'must|id',
		};

		// 取得数据
		let input = this.validateData(rules);

		let service = new QAService();
		return await service.deleteQA(input.id);
	}

	/** 获取历史记录 */
	async getHistory() {
		// 数据校验
		let rules = {
			page: 'must|int|default=1',
			size: 'int|default=20',
		};

		// 取得数据
		let input = this.validateData(rules);
		
		let service = new QAService();
		return await service.getHistory(this._userId, input.page, input.size);
	}

	/** 获取历史记录详情 */
	async getHistoryDetail() {
		// 数据校验
		let rules = {
			id: 'must|id',
		};

		// 取得数据
		let input = this.validateData(rules);
		
		let service = new QAService();
		return await service.getHistoryDetail(this._userId, input.id);
	}

	/** 删除历史记录 */
	async deleteHistory() {
		// 数据校验
		let rules = {
			id: 'must|id',
		};

		// 取得数据
		let input = this.validateData(rules);
		
		let service = new QAService();
		return await service.deleteHistory(this._userId, input.id);
	}

	/** 添加历史记录 */
	async addHistory() {
		// 数据校验
		let rules = {
			question: 'must|string|min:1|max:500|name=问题',
			answer: 'must|string|min:1|max:2000|name=答案',
			references: 'array|name=参考资料'
		};

		// 取得数据
		let input = this.validateData(rules);
		
		let service = new QAService();
		return await service.addHistory(this._userId, input);
	}
}

module.exports = QAController; 